package com.mnb.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    //获取年
    public static int getYear(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.YEAR);
    }

    //获取月
    public static int getMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.MONTH) + 1;
    }

    //获取日
    public static int getDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 替换给定日期的年份。
     *
     * @param originalDate 原始日期
     * @param newYear 新的年份
     * @return 替换年份后的日期
     */
    public static Date replaceYear(Date originalDate, int newYear) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(originalDate);
        calendar.set(Calendar.YEAR, newYear);
        return calendar.getTime();
    }



    public static Date decrementYear(Date originalDate,int v) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(originalDate);
        calendar.add(Calendar.YEAR, -v); // 减去1年
        return calendar.getTime();
    }

    // 截断 Date 对象到分钟级别
    public static Date truncateToMinute(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    public static String getMMddHHmm(Object date) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd HH:mm");
        try {
            Date d = inputFormat.parse(date.toString());
            return outputFormat.format(d);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean isSameMMddHHmm(Object date1, Object date2) {
        String formattedDate1 = getMMddHHmm(date1);
        String formattedDate2 = getMMddHHmm(date2);
        return formattedDate1 != null && formattedDate2 != null && formattedDate1.equals(formattedDate2);
    }
}
